package com.ferris.redbook.service.impl;

import com.ferris.redbook.dto.response.FileUploadResponse;
import com.ferris.redbook.service.FileService;
import com.ferris.redbook.util.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Value("${app.upload.base-path}")
    private String basePath;

    @Value("${app.storage.images-dir}")
    private String imagesDir;

    @Value("${app.storage.avatars-dir}")
    private String avatarsDir;

    @Value("${app.upload.access-url-base}")
    private String accessUrlBase;

    @Value("${app.upload.max-file-size}")
    private long maxFileSize;

    @Override
    public FileUploadResponse uploadImage(MultipartFile file) {
        return uploadFile(file, imagesDir, "images");
    }

    @Override
    public FileUploadResponse uploadAvatar(MultipartFile file) {
        return uploadFile(file, avatarsDir, "avatars");
    }

    private FileUploadResponse uploadFile(MultipartFile file, String subDir, String fileType) {
        // 验证文件
        validateFile(file);

        try {
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = FileUtil.getFileExtension(originalFilename);
            String newFilename = UUID.randomUUID().toString() + fileExtension;

            // 创建目标目录
            Path targetDir = Paths.get(basePath, subDir);
            if (!Files.exists(targetDir)) {
                Files.createDirectories(targetDir);
            }

            // 保存文件
            Path targetLocation = targetDir.resolve(newFilename);
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

            // 构建响应
            FileUploadResponse response = new FileUploadResponse();
            response.setUrl(accessUrlBase + "/" + fileType + "/" + newFilename);
            response.setName(originalFilename);
            response.setSize(file.getSize());
            response.setType(file.getContentType());

            return response;

        } catch (IOException ex) {
            throw new RuntimeException("文件上传失败: " + ex.getMessage(), ex);
        }
    }

    @Override
    public boolean deleteFile(String filePath) {
        try {
            Path path = Paths.get(filePath);
            return Files.deleteIfExists(path);
        } catch (IOException ex) {
            throw new RuntimeException("文件删除失败: " + ex.getMessage(), ex);
        }
    }

    private void validateFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new RuntimeException("文件不能为空");
        }

        if (file.getSize() > maxFileSize) {
            throw new RuntimeException("文件大小不能超过 " + (maxFileSize / 1024 / 1024) + "MB");
        }

        // 验证文件类型
        String originalFilename = file.getOriginalFilename();
        String extension = FileUtil.getFileExtension(originalFilename).toLowerCase();

        // 简单的文件类型验证
        if (!extension.matches("\\.(jpg|jpeg|png|gif|webp)$")) {
            throw new RuntimeException("不支持的文件格式。请上传图片文件");
        }
    }
}